var SIGN_REGEXP = /([yMdhsm])(\1*)/g;
var DEFAULT_PATTERN = 'yyyy-MM-dd';

function padding(s,len){
	var i;
	var len = len - (s + '').length;
	for(i = 0; i < len; i ++){
		s = '0' + s;
	}
	return s;
};

export default {
	/**
	 * 获取链接参数
	 * @param name
	 * @returns {string}
	 */
	getQueryStringByName:function(name){
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i");
		var r = window.location.search.substr(1).match(reg);
		var context = "";
		if(r != null)
			context = r[2];
		reg = null;
		r = null;
		return context == null || context == "" || context == "undefined"?"":context;
	},
	/**
	 * 日期格式化
	 */
	formatDate:{
		format:function(date,pattern){
			pattern = pattern || DEFAULT_PATTERN;
			return pattern.replace(SIGN_REGEXP,function($0){
				switch($0.charAt(0)){
					case 'y':
						return padding(date.getFullYear(),$0.length);
					case 'M':
						return padding(date.getMonth() + 1,$0.length);
					case 'd':
						return padding(date.getDate(),$0.length);
					case 'w':
						return padding(date.getDay() + 1,$0.length);
					case 'h':
						return padding(date.getHours(),$0.length);
					case 'm':
						return padding(date.getMinutes(),$0.length);
					case 's':
						return padding(date.getSeconds(),$0.length);
				}
			});
		},
		parse:function(dateString,pattern){
			var i;
			var sign;
			var _int;
			var _date;
			var matchs1 = pattern.match(SIGN_REGEXP);
			var matchs2 = dateString.match(/(\d)+/g);
			if(matchs1.length == matchs2.length){
				_date = new Date(1970,0,1);
				for(i = 0; i < matchs1.length; i ++){
					_int = parseInt(matchs2[i]);
					sign = matchs1[i];
					switch(sign.charAt(0)){
						case 'y':
							_date.setFullYear(_int);
							break;
						case 'M':
							_date.setMonth(_int - 1);
							break;
						case 'd':
							_date.setDate(_int);
							break;
						case 'h':
							_date.setHours(_int);
							break;
						case 'm':
							_date.setMinutes(_int);
							break;
						case 's':
							_date.setSeconds(_int);
							break;
					}
				}
				return _date;
			}
			return null;
		}
	},
	/**
	 * webSocketAPI
	 */
	webSocketAPI:{
		lockReconnect:false,//避免重复连接
		baseUrl:'ws://192.168.1.121:8099/javaWebSocket/webSocket/',
		wsUrl:null,
		timeout:3000,
		webSocket:null,
		tt:null,
		timeoutObj:null,
		serverTimeoutObj:null,
		_callback:null,
		channel:null,
		create:function(_callback,channel){
			try{
				this.wsUrl = this.baseUrl + channel;
				this.channel = channel;
				this.webSocket = new WebSocket(this.wsUrl);
				this._callback = _callback;
				this.init();
			}catch(e){
				this.reconnect();
			}
		},
		init:function(){
			this.webSocket.onopen = () =>{
				console.log('连接成功');
				//心跳检测重置
				this.heartCheck();
			};
			this.webSocket.onerror = () =>{
				console.log('发生异常了');
				this.reconnect();
			};
			this.webSocket.onmessage = (message) =>{
				if(message.data != "HeartBeat"){
					this._callback(message);
				}
				//拿到任何消息都说明当前连接是正常的
				this.heartCheck();
			}
			this.webSocket.onclose = ()=>{
				this.reconnect();
			};
		},
		reconnect:function(){
			if(this.lockReconnect){
				return;
			}
			this.lockReconnect = true;
			//没连接上会一直重连，设置延迟避免请求过多
			this.tt && clearTimeout(this.tt);
			this.tt = setTimeout(() =>{
				this.create(this._callback,this.channel);
				this.lockReconnect = false;
			},4000);
		},
		heartCheck:function(){
			clearTimeout(this.timeoutObj);
			clearTimeout(this.serverTimeoutObj);
			this.timeoutObj = setTimeout(() =>{
				var param = {
					'HeartBeat':'HeartBeat',
					'channel': this.channel
				};
				this.webSocket.send(JSON.stringify(param));
				this.serverTimeoutObj = setTimeout(() =>{//如果超过一定时间还没重置，
					this.webSocket.close();
				},this.timeout)
			},this.timeout)
		},
		close:function(){
			console.log('destroy关闭连接');
			this.webSocket.close();
		},
		sendMessage:function(message){
			message.channel = this.channel;
			this.webSocket.send(JSON.stringify(message));
		}
	}
};
